package com.client.core.service;

import com.client.core.ChatClient;
import com.common.MsgUtil;
import com.common.bean.SplitFileInfo;

import java.io.File;
import java.io.FileOutputStream;

public class FileStart implements Runnable {
    private String msg;

    public FileStart(String msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        //首次发文件过来，
        SplitFileInfo info = SplitFileInfo.info(msg);
        //检查目录下是否存在某些文件了，不存在，重0，存在了，最大开始发送，覆盖自己最大一次，保证文件OK的
        String wokerpath = System.getProperty("user.dir");
        //创建一个工作文件夹
        String s = wokerpath + File.separator + "workerFile" + File.separator + "receive";
        File file = new File(s);
        if (!file.exists()) {
            file.mkdirs();
        }

        File file1 = new File(s + File.separator + info.getFileName() + File.separator);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        try {
            FileOutputStream out = new FileOutputStream(file1.getAbsolutePath() + File.separator + info.getFileName() + "拆分说明.tmp");
            //拆分文件名，拆分份数，拆分大小，最后一次拆分大小，被拆分文件总大小
            out.write(msg.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println("接收的拆分文件保存失败");
        }

        String[] list = file1.list();
        if (list.length == 1) {
            //文件列表是空的，所以告诉对方，我要从0片文件开始给我发
            ChatClient.channel.writeAndFlush(MsgUtil.REQ_FILE(ChatService.me, ChatService.he, (info.getFileName() + ".1.tmp").getBytes()));
        } else {
            //找到最大的一片文件继续发
            int tempMax = 1;
            for (String s1 : list) {
                String[] split1 = s1.split("\\.");
                String s2 = split1[split1.length - 2];
                if (tempMax < getNum(s2)) {
                    tempMax = getNum(s2);
                }
            }
            ChatClient.channel.writeAndFlush(MsgUtil.REQ_FILE(ChatService.me, ChatService.he, (info.getFileName() + "." + tempMax + ".tmp").getBytes()));
        }
        System.out.println("拆分文件处理完毕，正在等待对方发送文件过来。。。。");
    }

    private Integer getNum(String res) {
        try {
            return Integer.parseInt(res);
        } catch (Exception e) {
            return -1;
        }
    }
}
